package com.ljf.framework.job;

import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;

/**
 * 说明：
 *
 * @Auther: lijinfeng
 * @Date: 2025/1/9
 */
public class LjfJobThread extends Thread{

    private final LjfLogService log = LjfLogManager.getLogger(LjfJobThread.class);

    private int jobId;
    private LjfJobHandler handler;
    private volatile boolean toStop = false;
    private String stopReason;

    public LjfJobThread(int jobId, LjfJobHandler handler) {
        this.jobId = jobId;
        this.handler = handler;
        // assign job thread name
        this.setName("ljf-job, JobThread-"+jobId+"-"+System.currentTimeMillis());
    }

    @Override
    public void run() {
        // init
        try {
            handler.init();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }

        // execute
        while(!toStop) {

            try {
                handler.execute();
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }

        // destroy
        try {
            handler.destroy();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }

    }

    /**
     * kill job thread
     *
     * @param stopReason
     */
    public void toStop(String stopReason) {
        /**
         * Thread.interrupt只支持终止线程的阻塞状态(wait、join、sleep)，
         * 在阻塞出抛出InterruptedException异常,但是并不会终止运行的线程本身；
         * 所以需要注意，此处彻底销毁本线程，需要通过共享变量方式；
         */
        this.toStop = true;
        this.stopReason = stopReason;
    }
}
